package flex.cc.nursing.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import flex.cc.PublicUtil;
import flex.cc.nursing.dao.NursingInterfaceLogDao;
import flex.cc.nursing.dao.NursingOrderDao;
import flex.cc.nursing.dao.NursingSynStatusDao;
import flex.cc.nursing.dto.entity.NursingInterfaceLogEntity;
import flex.cc.nursing.dto.entity.NursingOrderEntity;
import flex.cc.nursing.dto.entity.NursingSynStatusEntity;
import flex.cc.nursing.service.NursingSynStatusService;
import flex.cc.store.dao.StoreActivityConfigDao;
import flex.cc.store.dao.StoreCouponDao;
import flex.cc.store.dao.StoreOrderDao;
import flex.cc.store.dto.entity.StoreActivityConfigEntity;
import flex.cc.store.dto.entity.StoreCouponEntity;
import flex.cc.store.dto.entity.StoreOrderEntity;

/**
*
* @author R
* 2022年01月14日 13:35:01
* @desc 代驾单状态同步实现层
*/
@Service("nursingSynStatusService")
@Transactional(rollbackFor = Exception.class)
public class NursingSynStatusServiceImpl implements NursingSynStatusService {
    private static final Logger logger = LoggerFactory.getLogger(NursingSynStatusServiceImpl.class);
    
    @Autowired
    private NursingOrderDao nursingOrderDao;
    @Autowired
    private NursingInterfaceLogDao nursingInterfaceLogDao;
    @Autowired
    private NursingSynStatusDao nursingSynStatusDao;
    @Autowired
    private StoreCouponDao storeCouponDao;
    @Autowired
    private StoreOrderDao storeOrderDao;
    @Autowired
    private StoreActivityConfigDao activityConfigDao;
    
    /**
     * 护理类服务进度推送
     */
	@Override
	public JSONObject nursingSynStatus(Map<String, Object> requestBodyMap) {
		JSONObject jsonResult = new JSONObject();
		//预约单号
		String reserveNo = "";
		String transNo = "";
        String reqId = "";
        //卡券编码
        String couponNum = "";
        //同步状态
        String serviceStatus = "";
        //服务进度信息描述
        String serviceInfo = "";
        //链接
        String url = "";
        //处理时间
        Date serviceTime = null;
        JSONObject jsonObj=new JSONObject(requestBodyMap);
        //请求报文
		String requestBody = jsonObj.toString();
		try {
			JSONObject busBodyObj = (JSONObject) requestBodyMap.get("bus_body");
            Map<String, Object> busBodyMap = busBodyObj.toJavaObject(Map.class);
            
            JSONObject requestCommonObj = (JSONObject) requestBodyMap.get("common");
            Map<String, Object> requestCommonMap = requestCommonObj.toJavaObject(Map.class);

            transNo = (String) requestCommonMap.get("transNo");
            reqId = (String) requestCommonMap.get("reqId");
            //预约单号
			reserveNo = (String) busBodyMap.get("reserveNo");
			if(PublicUtil.isNotEmpty(reserveNo)){
				Map<String,String> orderParamMap = new HashMap<String,String>();
				orderParamMap.put("orderNo", reserveNo);
				NursingOrderEntity nursingOrderEntity = nursingOrderDao.getOneByParams(orderParamMap);
				if(PublicUtil.isNotEmpty(nursingOrderEntity)){
					couponNum = nursingOrderEntity.getOrderId();
				}
			}
			
			//当前服务进度
			serviceStatus = (String) busBodyMap.get("serviceStatus");
			//服务进度信息描述
			serviceInfo = (String) busBodyMap.get("serviceInfo");
			//链接
			JSONArray urlListArr = (JSONArray) busBodyMap.get("urlList");
			if(PublicUtil.isNotEmpty(urlListArr)){
				url = (String) urlListArr.get(0);
			}
			//处理时间  时间戳转日期
			serviceTime = new Date(Long.parseLong(String.valueOf(busBodyMap.get("serviceTime"))));
			
			if(PublicUtil.isEmpty(reserveNo)) {
				JSONObject commonResult = new JSONObject();
				commonResult.put("transNo", transNo);
				commonResult.put("reqId", reqId);
				commonResult.put("resTime", flex.cc.common.utils.DateUtil.getCurrentDate("yyyy-MM-dd HH:mm:ss.SSS"));
				commonResult.put("resCode", "111");
				commonResult.put("resMsg", "操作失败");
				
				JSONObject busBodyResult = new JSONObject();
				busBodyResult.put("reserveNo", "");
				busBodyResult.put("bussResCode", "99");
				busBodyResult.put("bussResMsg", "该订单业务处理错误，错误信息为：预约单号不能为空");
				
				jsonResult.put("bus_body", busBodyResult);
				jsonResult.put("common", commonResult);
				String responseBody = jsonResult.toJSONString();
				//保存服务进度以及接口日志
				insertSynDate(reserveNo,couponNum,serviceStatus,serviceInfo,
						url,serviceTime,requestBody,responseBody,"1");
				
	            return jsonResult;
			}
			
			if(PublicUtil.isEmpty(serviceStatus)) {
				JSONObject commonResult = new JSONObject();
				commonResult.put("transNo", transNo);
				commonResult.put("reqId", reqId);
				commonResult.put("resTime", flex.cc.common.utils.DateUtil.getCurrentDate("yyyy-MM-dd HH:mm:ss.SSS"));
				commonResult.put("resCode", "111");
				commonResult.put("resMsg", "操作失败");
				
				JSONObject busBodyResult = new JSONObject();
				busBodyResult.put("reserveNo", reserveNo);
				busBodyResult.put("bussResCode", "99");
				busBodyResult.put("bussResMsg", "该订单业务处理错误，错误信息为：当前服务进度不能为空");
				
				jsonResult.put("bus_body", busBodyResult);
				jsonResult.put("common", commonResult);
				String responseBody = jsonResult.toJSONString();
				//保存服务进度以及接口日志
				insertSynDate(reserveNo,couponNum,serviceStatus,serviceInfo,
						url,serviceTime,requestBody,responseBody,"1");
				
	            return jsonResult;
			}
			
			if(PublicUtil.isEmpty(serviceInfo)) {
				JSONObject commonResult = new JSONObject();
				commonResult.put("transNo", transNo);
				commonResult.put("reqId", reqId);
				commonResult.put("resTime", flex.cc.common.utils.DateUtil.getCurrentDate("yyyy-MM-dd HH:mm:ss.SSS"));
				commonResult.put("resCode", "111");
				commonResult.put("resMsg", "操作失败");
				
				JSONObject busBodyResult = new JSONObject();
				busBodyResult.put("reserveNo", reserveNo);
				busBodyResult.put("bussResCode", "99");
				busBodyResult.put("bussResMsg", "该订单业务处理错误，错误信息为：服务进度信息描述不能为空");
				
				jsonResult.put("bus_body", busBodyResult);
				jsonResult.put("common", commonResult);
				String responseBody = jsonResult.toJSONString();
				//保存服务进度以及接口日志
				insertSynDate(reserveNo,couponNum,serviceStatus,serviceInfo,
						url,serviceTime,requestBody,responseBody,"1");
				
	            return jsonResult;
			}
			
			//按照状态同步接口返回的状态更新预约服务单
			Map<String, Object> orderParam = new HashMap<String, Object>();
			orderParam.put("status", serviceStatus);
			orderParam.put("orderNo", reserveNo);
			orderParam.put("updateTime", new Date());
			nursingOrderDao.updateByParams(orderParam);
			
			JSONObject commonResult = new JSONObject();
			commonResult.put("transNo", transNo);
			commonResult.put("reqId", reqId);
			commonResult.put("resTime", flex.cc.common.utils.DateUtil.getCurrentDate("yyyy-MM-dd HH:mm:ss.SSS"));
			commonResult.put("resCode", "000");
			commonResult.put("resMsg", "操作成功");
			
			JSONObject busBodyResult = new JSONObject();
			busBodyResult.put("reserveNo", reserveNo);
			busBodyResult.put("bussResCode", "0");
			busBodyResult.put("bussResMsg", "处理成功");
			
			jsonResult.put("bus_body", busBodyResult);
			jsonResult.put("common", commonResult);
			String responseBody = jsonResult.toJSONString();
			insertSynDate(reserveNo,couponNum,serviceStatus,serviceInfo,
					url,serviceTime,requestBody,responseBody,"0");
			
			/**
			 * 卡券下所有预约服务的状态均为13已完成/10已取消时，该卡券状态为已使用
			 */
			//获取卡券信息
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("couponNum", couponNum);
			StoreCouponEntity couponEntity = storeCouponDao.getOneByParams(params);
			if(PublicUtil.isNotEmpty(couponEntity)){
				//服务单号
				String orderId = couponEntity.getOrderId();
				//获取服务包订单信息
				StoreOrderEntity storeOrderEntity = storeOrderDao.queryByOrderId(orderId);
				
				if(PublicUtil.isNotEmpty(storeOrderEntity)){
					//服务包配置编码
					String configCode = storeOrderEntity.getServiceItemCode();
					//获取服务商
					String provider = couponEntity.getServer();
					//获取服务项目编码
					String activityId = couponEntity.getActivityId();
					
					//获取服务包内容配置
					Map<String, Object> reqVo = new HashMap<String, Object>();
					reqVo.put("configCode", configCode);
					reqVo.put("activityCode", activityId);
					reqVo.put("provider", provider);
					List<StoreActivityConfigEntity> activityConfigList = activityConfigDao.queryActivityConfig(reqVo);
					if(activityConfigList.size()>0){
						StoreActivityConfigEntity activityConfig = activityConfigList.get(0);
						//获取使用次数
						int usageCount = activityConfig.getUsageCount();
						
						//获取当前卡券预约的所有记录 并且状态为11或者10
						List<String> statusList = new ArrayList<String>();
						statusList.add("10");
						statusList.add("11");
						Map<String, Object> paramMap = new HashMap<String, Object>();
						paramMap.put("orderId", couponNum);
						paramMap.put("statusList", statusList);
						List<NursingOrderEntity> nursingOrderEntityList = nursingOrderDao.queryNursingOrderList(paramMap);
						if(nursingOrderEntityList.size()>0){
							//状态为11或者13的卡券记录条数与使用次数相等 将卡券状态置为已使用
							if(nursingOrderEntityList.size()==usageCount){
								Map<String, Object> paramsMap = new HashMap<String, Object>();
								paramsMap.put("couponNum", couponNum);
								paramsMap.put("status", "3");
								storeCouponDao.updateByParam(paramsMap);
							}
						}
					}
				}
			}
			
			
	    	return jsonResult;
		}catch (Exception e) {
			logger.info("护理服务进度信息推送接口异常"+e.getMessage());

			JSONObject commonResult = new JSONObject();
			commonResult.put("transNo", transNo);
			commonResult.put("reqId", reqId);
			commonResult.put("resTime", flex.cc.common.utils.DateUtil.getCurrentDate("yyyy-MM-dd HH:mm:ss.SSS"));
			commonResult.put("resCode", "111");
			commonResult.put("resMsg", "操作失败");
			
			JSONObject busBodyResult = new JSONObject();
			busBodyResult.put("reserveNo", reserveNo);
			busBodyResult.put("bussResCode", "99");
			busBodyResult.put("bussResMsg", "该订单业务处理错误，错误信息为：服务进度信息推送接口处理异常");
			
			jsonResult.put("bus_body", busBodyResult);
			jsonResult.put("common", commonResult);
			String responseBody = jsonResult.toJSONString();
			insertSynDate(reserveNo,couponNum,serviceStatus,serviceInfo,
					url,serviceTime,requestBody,responseBody,"1");
			
            return jsonResult;
		}
	}
    
	/**
	 * 新增状态同步记录以及接口请求日志
	 * @param reserveNo  预约单号
	 * @param couponNum  卡券编码
	 * @param serviceStatus 同步状态
	 * @param serviceInfo 服务进度信息描述
	 * @param url 链接
	 * @param serviceTime  处理时间 
	 * @param requestBody  请求报文
	 * @param responseBody 响应报文
	 * @param status       请求状态  0成功 1失败
	 */
	private void insertSynDate(String reserveNo,String couponNum,String serviceStatus,String serviceInfo,
			String url,Date serviceTime,String requestBody,String responseBody,String status){
		/**
		 * 因为服务进度"正在等待安排评估人员,请耐心等待" 再预约时候默认插入 先查询当前是否存在 如果存在更新，不存在新增
		 */
		if(serviceStatus.equals("1")){
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("reserveNo", reserveNo);
			params.put("serviceStatus", "1");
			//获取服务进度"正在等待安排评估人员,请耐心等待"的服务进度同步记录
			NursingSynStatusEntity nursingSynStatusEntity = nursingSynStatusDao.queryOneByParams(params);
			/**
			 * 如果存在服务进度"正在等待安排评估人员,请耐心等待"的服务进度同步 且当前推送进度是"正在等待安排评估人员,请耐心等待"
			 * 需更新该服务进度记录
			 */
			if(PublicUtil.isNotEmpty(nursingSynStatusEntity)){
				Map<String, Object> paramMap = new HashMap<String, Object>();
				paramMap.put("url", url);
				paramMap.put("serviceTime", serviceTime);
				paramMap.put("createTime", new Date());
				paramMap.put("updateTime", new Date());
				paramMap.put("reserveNo", reserveNo);
				nursingSynStatusDao.updateByParams(paramMap);
			}
		}else{
			NursingSynStatusEntity nursingSynStatusEntity = new NursingSynStatusEntity();
			nursingSynStatusEntity.setReserveNo(reserveNo);
			nursingSynStatusEntity.setCouponNum(couponNum);
			nursingSynStatusEntity.setServiceStatus(serviceStatus);
			nursingSynStatusEntity.setServiceInfo(serviceInfo);
			nursingSynStatusEntity.setUrl(url);
			nursingSynStatusEntity.setServiceTime(serviceTime);
			nursingSynStatusEntity.setCreater("admin");
			nursingSynStatusEntity.setCreateTime(new Date());
			nursingSynStatusEntity.setUpdater("admin");
			nursingSynStatusEntity.setUpdateTime(new Date());
			nursingSynStatusEntity.setIsDelete(0);
			nursingSynStatusDao.insert(nursingSynStatusEntity);
		}
		
		NursingInterfaceLogEntity nursingInterfaceLogEntity = new NursingInterfaceLogEntity();
    	nursingInterfaceLogEntity.setOrderNo(reserveNo);
    	nursingInterfaceLogEntity.setOrderId(couponNum);
    	nursingInterfaceLogEntity.setStatus(status);
    	nursingInterfaceLogEntity.setInterfaceName("服务进度信息推送接口");
    	nursingInterfaceLogEntity.setRequestTime(new Date());
    	nursingInterfaceLogEntity.setRequestBody(requestBody);
    	nursingInterfaceLogEntity.setResponseBody(responseBody);
    	nursingInterfaceLogEntity.setResponseTime(new Date());
    	nursingInterfaceLogEntity.setCreateTime(new Date());
    	nursingInterfaceLogDao.insert(nursingInterfaceLogEntity);
	}
	
    /**
     * @param params 查询条件
     * @return
     * @description 根据查询参数，获取护理单状态
     * @author wkangle
     * @time 2022/03/23 0023 13:45
     * @exception/throws
     */
    @Override
    public NursingSynStatusEntity queryOneByParams(Map<String, Object> params) {
        return nursingSynStatusDao.queryOneByParams(params);
    }


}
